<?php

namespace App\Admin\Extensions\Async;

use App\Http\Library\JuHeCarBrand;
use App\Models\CarBrand;
use Dcat\Admin\Grid\Tools\AbstractTool;
use Illuminate\Http\Client\RequestException;

class AsyncCardBrand extends AbstractTool
{
    /**
     * 按钮样式定义，默认 btn btn-white waves-effect
     *
     * @var string
     */
    protected $style = 'btn btn-info waves-effect';


    // 注意action的构造方法参数一定要给默认值
    public function __construct()
    {

    }
    /**
     * 按钮文本
     *
     * @return string|void
     */
    public function title()
    {
        return '同步聚合汽车品牌';
    }

    public function confirm()
    {
        return '您确定要同步聚合汽车品牌大全数据吗？';
    }

    // 处理请求
    public function handle()
    {
        try {
            $res = JuHeCarBrand::getBrands();
            if ($res['error_code']){
                throw new \Exception($res['reason']);
            }
            $result = $res['result'];
            $num = 0;
            if ($result){
                foreach ($result as $item){
                    $carBrand =  CarBrand::whereId($item['id'])->first();
                    if (!$carBrand){
                       $carBrand = new CarBrand();
                    }
                    $carBrand->prefix = $item['first_letter'];
                    $carBrand->name = $item['brand_name'];
                    $carBrand->logo = $item['brand_logo'];
                    $res = $carBrand->save();
                    if ($res){
                        $num++;
                    }
                }
            }
        }catch (\Exception|RequestException $e){
            return $this->response()->error($e->getMessage());
        }
        if ($num){
            return $this->response()->success("同步成功!")->refresh();
        }else{
            return $this->response()->warning("暂无数据同步!");
        }
    }
}
